package com.swz.dcrm.ui.daily;


import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.DailyCustomer;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;

import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;

import com.swz.dcrm.R;
import com.swz.dcrm.ui.viewmodel.AnalyzeViewModel;
import com.swz.dcrm.util.Tool;

import java.util.ArrayList;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class DaliyCustomerFragment extends BaseFragment {


    @Inject
    AnalyzeViewModel analyzeViewModel;
    @BindView(R.id.pie_chart1)
    PieChart pieChart1;
    @BindView(R.id.tv_one_month)
    TextView tvOneMonth;
    @BindView(R.id.tv_two_month)
    TextView tvTwoMonth;
    @BindView(R.id.pie_chart2)
    PieChart pieChart2;
    @BindView(R.id.tv_in_stock_car)
    TextView tvInstockCar;
    @BindView(R.id.tv_booking_car)
    TextView tvBookingCar;


    public static DaliyCustomerFragment newInstance() {

        return new DaliyCustomerFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())) {
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        analyzeViewModel.getDailyCustomer().observe(this, new Observer<BaseResponse<DailyCustomer>>() {
            @Override
            public void onChanged(BaseResponse<DailyCustomer> dailyCustomerBaseResponse) {
                if (dailyCustomerBaseResponse == null) {
                    return;
                }
                if (dailyCustomerBaseResponse.isSuccess()) {
                    DailyCustomer dailyCustomer=dailyCustomerBaseResponse.getData();
                    String str=dailyCustomer.getInStockCarCount()+"("+
                            dailyCustomer.getInStockCarRate()+"%)";
                    tvInstockCar.setText(getSpannableString(str,'(',R.color.black_2f3234,R.color.black_2f3234,0));
                    str=dailyCustomer.getBookCarCount()+"("+
                            dailyCustomer.getBookCarRate()+"%)";
                    tvBookingCar.setText(getSpannableString(str,'(',R.color.black_2f3234,R.color.black_2f3234,0));
                    str=dailyCustomer.getOneMonthUnsettledCount()+"("+
                            dailyCustomer.getOneMonthUnsettledRate()+"%)";
                    tvOneMonth.setText(getSpannableString(str,'(',R.color.black_2f3234,R.color.black_2f3234,0));
                    str=dailyCustomer.getTwoMonthUnsettledCount()+"("+
                            dailyCustomer.getTwoMonthUnsettledRate()+"%)";
                    tvTwoMonth.setText(getSpannableString(str,'(',R.color.black_2f3234,R.color.black_2f3234,0));

                    if((dailyCustomer.getBookCarCount()+
                            dailyCustomer.getInStockCarCount())>0) {
                        int[] ints = new int[]{dailyCustomer.getInStockCarCount(),
                                dailyCustomer.getBookCarCount()};
                        initPieChart(pieChart1,ints);
                    }else {
                        pieChart1.setNoDataText("暂无此类型数据");
                        pieChart1.invalidate();
                    }

                    if((dailyCustomer.getOneMonthUnsettledCount()+
                            dailyCustomer.getTwoMonthUnsettledCount())>0){

                        int [] ints1=new int[]{dailyCustomer.getOneMonthUnsettledCount(),
                                dailyCustomer.getTwoMonthUnsettledCount()};
                        initPieChart(pieChart2,ints1);
                    }else {
                        pieChart2.setNoDataText("暂无此类型数据");
                        pieChart2.invalidate();
                    }
                }
            }
        });

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onLoadRetry();
    }

    @Override
    public int layoutId() {
        return R.layout.fragment_daliy_customer;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        return false;
    }

    public SpannableString getSpannableString(String str, char splitChar, int color1, int color2, int offset){
        AbsoluteSizeSpan absoluteSizeSpan12;
        AbsoluteSizeSpan absoluteSizeSpan18;
        ForegroundColorSpan foregroundColorSpanlight;
        ForegroundColorSpan foregroundColorSpanDark;


        absoluteSizeSpan12=new AbsoluteSizeSpan(Tool.dip2px(getActivity(),12));
        absoluteSizeSpan18=new AbsoluteSizeSpan(Tool.dip2px(getActivity(),18));
        foregroundColorSpanlight=new ForegroundColorSpan(getResources().getColor(color1));
        foregroundColorSpanDark=new ForegroundColorSpan(getResources().getColor(color2));

        SpannableString spannableString = new SpannableString(str);

        spannableString.setSpan(foregroundColorSpanlight, 0,str.indexOf(splitChar), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(absoluteSizeSpan18,0,str.indexOf(splitChar),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(foregroundColorSpanDark, str.indexOf(splitChar)+offset,str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(absoluteSizeSpan12,str.indexOf(splitChar)+offset,str.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    public void initPieChart(PieChart pieChart, int[] data) {

        Description description = new Description();
//        description.setText("需要展示的内容");
        description.setEnabled(false);
        pieChart.setDescription(description);
        // 设置中心圆孔半径占整个饼状图半径的百分比（100f 是最大=整个图表的半径），默认的50％的百分比（即50f）。
        pieChart.setDrawHoleEnabled(false);
        // 设置中间文字中大小
        pieChart.setCenterTextSize(12f);
        // 百分比显示
        pieChart.setUsePercentValues(true);
        // 禁用触摸
        pieChart.setTouchEnabled(false);
        //设置内置图例不显示
        pieChart.getLegend().setEnabled(false);
        // 设置隐藏饼图上文字，只显示百分比
        pieChart.setDrawSliceText(false);


        //数值
        ArrayList<PieEntry> values = new ArrayList<PieEntry>();
        //数值描述
        ArrayList<String> valuesLabels = new ArrayList<>();
        //颜色
        int[] colors = new int[2];

        //添加颜色

        colors[0] = getResources().getColor(R.color.blue_0f6eff);

        colors[1] = getResources().getColor(R.color.orange_ffbd30);

        for (int i = 0; i < 2; i++) {
            //添加数值
            values.add(new PieEntry(data[i], i));
            //添加数值描述
            PieDataSet pieDataSet = new PieDataSet(values, "");
            pieDataSet.setSliceSpace(2f);
            pieDataSet.setValueTextColor(Color.WHITE);
            pieDataSet.setValueTextSize(12f);
            //将随机的颜色设置进来
            pieDataSet.setColors(colors);
            PieData pieData = new PieData();
            pieData.setDataSet(pieDataSet);
            //设置百分比显示
            pieData.setDrawValues(false);
            //set data...
            pieChart.setData(pieData);
            pieChart.invalidate();
        }
    }
}
